package com.swak.boot.config.job;

import static com.swak.boot.Application.APP_LOGGER;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.swak.Constants;
import com.swak.boot.config.job.queue.GuavaQueueAutoConfiguration;
import com.swak.boot.config.job.queue.RabbitmqQueueAutoConfiguration;
import com.swak.job.JobConfig;
import com.swak.job.JobService;
import com.swak.utils.StringUtils;
import com.swak.vertx.transport.VertxProxy;

/**
 * 简单的定时任务
 * 
 * @author lifeng
 */
@Configuration
@ConditionalOnClass(JobService.class)
@EnableConfigurationProperties(JobProperties.class)
@Import({ JobStorageAutoConfiguration.class, RabbitmqQueueAutoConfiguration.class, GuavaQueueAutoConfiguration.class,
		JobManagerAutoConfiguration.class })
@ConditionalOnProperty(prefix = Constants.APPLICATION_PREFIX, name = "enableJob", matchIfMissing = true)
public class JobAutoConfiguration {

	@Autowired
	private JobProperties properties;
	@Autowired
	private ApplicationContext context;

	public JobAutoConfiguration() {
		APP_LOGGER.debug("Loading Job");
	}

	/**
	 * 自动注册任务
	 * 
	 * @return
	 */
	@Bean
	public JobPostProcessor jobPostProcessor() {
		return new JobPostProcessor();
	}

	/**
	 * 任务管理
	 * 
	 * @return
	 */
	@Bean
	public JobService jobService(VertxProxy vertxProxy) {
		JobConfig config = new JobConfig().setScheduler(properties.getScheduler()).setConfigs(properties.getConfigs())
				.setApplicationName(context.getEnvironment().getProperty(Constants.Application_Name))
				.setModule(StringUtils.defaultIfBlank(properties.getModule(),
						context.getEnvironment().getProperty(Constants.Application_Name)));
		if (config.getWorkerPoolSize() <= 0) {
			config.setWorkerPoolSize(vertxProxy.config().getWorkerPoolSize());
		}
		return new JobService(config);
	}
}
